let my_code = null
let redirectURL = ''
const app = getApp()
Page({
  data: {
    countDownVisible: false,
    mobile: '',
    code: '',
  },
  onLoad(options) {
    console.log(options)
    redirectURL = options.redirectURL
  },

  countDownChange(ev) {
    this.setData({
      timeData: ev.detail,
      countDownVisible: ev.detail.minutes === 1 || ev.detail.seconds > 0,
    })
  },

  //2.获取短信验证码
  async getcode() {
    // 2.1进行校验

    if (!wx.verify.verifyMobile(this.data.mobile)) return
    //  2.2开启倒计时
    this.setData({
      countDownVisible: true,
    })
    // 2.3后台获取数据
    const { code, data } = await wx.http.get('/code', { mobile: this.data.mobile })
    if (code !== 10000) return
    console.log(data.code)
    my_code = data.code
  },
  // 3.复制验证码到粘贴板
  copyCode() {
    wx.setClipboardData({
      data: my_code,
    })
  },
  // 4,登录/注册
  async login() {
    const { mobile, code } = this.data
    // console.log(111111111111);
    // 校验手机号验证码
    if (!wx.verify.verifyMobile(this.data.mobile)) return
    if (!wx.verify.verifyCode(this.data.code)) return
    // console.log(111111111111)
    // 4.2调用接口登录/注册接口
    const res = await wx.http.post('/login', { mobile, code })
    if (res.code !== 10000) return wx.utils.toast('登录失败')
    app.setToken(res.data.token)
    app.setRefreshToken(res.data.refreshToken)
    wx.utils.toast('登录成功')
    if (redirectURL === '/pages/my/index') {
      wx.switchTab({
        url: redirectURL,
      })
    } else {
      // 重定向到原本要访问的页面
      wx.redirectTo({
        url: redirectURL,
      })
    }

    console.log(redirectURL)
  },
})
